package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"laundry-service/app/client/internal/svc"
	"laundry-service/app/client/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListOrderLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewListOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListOrderLogic {
	return &ListOrderLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ListOrderLogic) ListOrder(req *types.OrderlistReq) (resp *types.OrderlistReply, err error) {
	userId, _ := l.ctx.Value("userId").(json.Number).Int64()
	req.UserId = int(userId)
	fmt.Println("userId:", userId)
	
	data, cn, err := l.svcCtx.Db.ListOrder(req)
	if err != nil {
		return nil, err
	}
	result := make([]*types.Orderlist, 0)

	for _, v := range data {
		res := new(types.Orderlist)
		res.ID = v.ID
		res.Number = v.Number
		res.State = v.State
		res.Amount = v.Amount
		res.RealAmount = v.RealAmount
		res.Num = v.Num
		res.CreatedAt = v.CreatedAt.Format("2006-01-02 15:04:05")
		oi, _ := l.svcCtx.Db.GetOrderItem(v.ID)
		p := make([]*types.Product, 0)
		for _, i := range oi {
			resp := new(types.Product)
			resp.ID = i.ID
			resp.Name = i.Name
			resp.Price = i.Price
			resp.Url = i.Url
			p = append(p, resp)
		}
		res.Product = p
		result = append(result, res)
	}

	rsp := new(types.OrderlistReply)
	rsp.Cn = cn
	rsp.Data = result
	return rsp, nil
}
